/**
 * 数据源管理主页面组件
 * 严格遵循DataPlexus现有管理页面的组件结构和样式
 */

import React, { useState, useEffect, useCallback, useMemo, useRef } from 'react';
import {
  Card,
  Table,
  Button,
  Space,
  Input,
  Select,
  Tag,
  Tooltip,
  Modal,
  message,
  Row,
  Col,
  Typography,
  Popconfirm,
  Dropdown,
  Badge
} from 'antd';
import type { ColumnsType, TableProps } from 'antd/es/table';
import {
  PlusOutlined,
  ReloadOutlined,
  DatabaseOutlined,
  ExperimentOutlined,
  EditOutlined,
  DeleteOutlined,
  MoreOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  QuestionCircleOutlined
} from '@ant-design/icons';

import { PermissionGuard, ActionGuard } from '../components/PermissionGuard';
import DataSourceForm from '../components/DataSourceForm';
import DataSourceTestModal from '../components/DataSourceTestModal';
import { useAuth } from '../contexts/AuthContext';
import { requestGuard } from '../utils/requestGuard';
import { datasourceApi } from '../services/datasourceApi';

// Temporary debug import - remove after testing
if (process.env.NODE_ENV === 'development') {
  import('../utils/debugDataSourcePage');
}

import type {
  DataSource,
  DataSourceCreate,
  DataSourceUpdate,
  DataSourceQueryParams,
  DatabaseType,
  TestStatus,
  PaginationConfig
} from '../types/datasource';
import {
  DatabaseTypeLabels,
  TestStatusLabels,
  TestStatusColors
} from '../types/datasource';

const { Search } = Input;
const { Option } = Select;
const { Title, Text } = Typography;

const DataSourceManagement: React.FC = () => {
  // 状态管理
  const [loading, setLoading] = useState(false);
  const [datasources, setDatasources] = useState<DataSource[]>([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<number[]>([]);
  const [searchText, setSearchText] = useState('');
  const [selectedType, setSelectedType] = useState<DatabaseType | undefined>();
  const [selectedStatus, setSelectedStatus] = useState<boolean | undefined>();
  const [selectedTestStatus, setSelectedTestStatus] = useState<TestStatus | undefined>();
  
  // 分页配置
  const [pagination, setPagination] = useState<PaginationConfig>({
    current: 1,
    pageSize: 10,
    total: 0,
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
  });

  // 模态框状态
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [isTestModalVisible, setIsTestModalVisible] = useState(false);
  const [editingDataSource, setEditingDataSource] = useState<DataSource | null>(null);
  const [testingDataSource, setTestingDataSource] = useState<DataSource | null>(null);

  // 权限和认证
  const { hasPermission } = useAuth();
  
  // 防抖搜索的ref
  const searchTimeoutRef = useRef<NodeJS.Timeout>();
  const fetchDataSourcesRef = useRef<() => void>();

  // 防止重复请求的ref
  const isLoadingDataSourcesRef = useRef(false);

  // 权限检查 - 使用useMemo避免重复计算，遵循其他管理页面的模式
  const permissions = useMemo(() => ({
    canView: hasPermission('datasource.view'),
    canCreate: hasPermission('datasource.create'),
    canUpdate: hasPermission('datasource.update'),
    canDelete: hasPermission('datasource.delete'),
    canTest: hasPermission('datasource.test'),
    canManage: hasPermission('datasource.manage')
  }), [hasPermission]);

  /**
   * 获取数据源列表 - 使用requestGuard防止重复请求
   */
  const fetchDataSources = useCallback(async (forceRefresh: boolean = false) => {
    const currentParams: DataSourceQueryParams = {
      page: pagination.current,
      page_size: pagination.pageSize,
      search: searchText || undefined,
      db_type: selectedType,
      is_active: selectedStatus,
      test_status: selectedTestStatus
    };

    // 使用requestGuard防止重复请求，但允许强制刷新
    if (!forceRefresh && !requestGuard.canRequest('fetchDataSources', currentParams)) {
      return;
    }

    if (isLoadingDataSourcesRef.current) {
      return;
    }

    setLoading(true);
    isLoadingDataSourcesRef.current = true;

    try {
      const response = await datasourceApi.getDatasources(currentParams);

      setDatasources(response.datasources);
      setPagination(prev => ({
        ...prev,
        total: response.total,
        current: response.page,
        pageSize: response.page_size
      }));
    } catch (error: any) {
      // 错误已在API服务中处理
      console.error('获取数据源列表失败:', error);
    } finally {
      requestGuard.completeRequest('fetchDataSources');
      setLoading(false);
      isLoadingDataSourcesRef.current = false;
    }
  }, [pagination.current, pagination.pageSize, searchText, selectedType, selectedStatus, selectedTestStatus]);

  // 保存fetchDataSources引用
  fetchDataSourcesRef.current = fetchDataSources;

  /**
   * 触发数据获取的包装函数 - 避免useEffect依赖问题
   */
  const triggerDataFetch = useCallback(() => {
    fetchDataSources(true); // 强制刷新，绕过requestGuard
  }, [fetchDataSources]);

  /**
   * 初始化数据获取 - 只在组件挂载时执行一次，遵循其他管理页面的模式
   */
  useEffect(() => {
    if (!permissions.canView) return;

    // 清除可能存在的请求防护状态（页面刷新时）
    requestGuard.clearGuard('fetchDataSources');

    // 获取数据源数据
    triggerDataFetch();
  }, [permissions.canView]); // 移除函数依赖，避免无限循环

  /**
   * 分页和搜索条件变化时获取数据源数据
   */
  useEffect(() => {
    if (!permissions.canView) return;

    fetchDataSources();
  }, [permissions.canView, fetchDataSources]);

  /**
   * 搜索和筛选条件变化时的处理 - 使用防抖
   */
  useEffect(() => {
    if (!permissions.canView) return;

    // 清除之前的定时器
    if (searchTimeoutRef.current) {
      clearTimeout(searchTimeoutRef.current);
    }

    // 设置新的定时器
    searchTimeoutRef.current = setTimeout(() => {
      // 重置到第一页
      setPagination(prev => ({ ...prev, current: 1 }));
      // 注意：不在这里直接调用fetchDataSources，让分页useEffect处理
    }, 300); // 300ms防抖

    // 清理函数
    return () => {
      if (searchTimeoutRef.current) {
        clearTimeout(searchTimeoutRef.current);
      }
    };
  }, [permissions.canView, searchText, selectedType, selectedStatus, selectedTestStatus]);

  /**
   * 组件卸载时清理定时器
   */
  useEffect(() => {
    return () => {
      if (searchTimeoutRef.current) {
        clearTimeout(searchTimeoutRef.current);
      }
    };
  }, []);

  /**
   * 处理搜索 - 300ms防抖
   */
  const handleSearch = useCallback((value: string) => {
    // 清除之前的定时器
    if (searchTimeoutRef.current) {
      clearTimeout(searchTimeoutRef.current);
    }

    // 设置新的定时器
    searchTimeoutRef.current = setTimeout(() => {
      setSearchText(value);
      setPagination(prev => ({ ...prev, current: 1 }));
    }, 300);
  }, []);

  /**
   * 处理筛选变化
   */
  const handleFilterChange = useCallback((type: 'type' | 'status' | 'testStatus', value: any) => {
    switch (type) {
      case 'type':
        setSelectedType(value);
        break;
      case 'status':
        setSelectedStatus(value);
        break;
      case 'testStatus':
        setSelectedTestStatus(value);
        break;
    }
    setPagination(prev => ({ ...prev, current: 1 }));
  }, []);

  /**
   * 处理表格变化 - 使用useCallback优化
   */
  const handleTableChange: TableProps<DataSource>['onChange'] = useCallback((paginationConfig) => {
    setPagination(prev => ({
      ...prev,
      current: paginationConfig.current || 1,
      pageSize: paginationConfig.pageSize || 10
    }));
  }, []);

  /**
   * 打开创建/编辑模态框
   */
  const openModal = useCallback((dataSource?: DataSource) => {
    setEditingDataSource(dataSource || null);
    setIsModalVisible(true);
  }, []);

  /**
   * 关闭模态框
   */
  const closeModal = useCallback(() => {
    setIsModalVisible(false);
    setEditingDataSource(null);
  }, []);

  /**
   * 打开测试模态框
   */
  const openTestModal = useCallback((dataSource: DataSource) => {
    setTestingDataSource(dataSource);
    setIsTestModalVisible(true);
  }, []);

  /**
   * 关闭测试模态框
   */
  const closeTestModal = useCallback(() => {
    setIsTestModalVisible(false);
    setTestingDataSource(null);
  }, []);

  /**
   * 提交表单
   */
  const handleSubmit = useCallback(async (values: DataSourceCreate | DataSourceUpdate) => {
    try {
      if (editingDataSource) {
        // 更新数据源
        await datasourceApi.updateDatasource(editingDataSource.id, values as DataSourceUpdate);
      } else {
        // 创建数据源
        await datasourceApi.createDatasource(values as DataSourceCreate);
      }
      
      closeModal();
      // 刷新数据源列表
      await fetchDataSources();
    } catch (error: any) {
      // 错误已在API服务中处理
    }
  }, [editingDataSource, closeModal, fetchDataSources]);

  /**
   * 删除数据源
   */
  const handleDelete = useCallback(async (id: number) => {
    try {
      await datasourceApi.deleteDatasource(id);
      // 刷新数据源列表
      await fetchDataSources();
    } catch (error: any) {
      // 错误已在API服务中处理
    }
  }, [fetchDataSources]);

  /**
   * 测试数据源连接
   */
  const handleTest = useCallback(async (dataSource: DataSource) => {
    try {
      await datasourceApi.testDatasourceConnection(dataSource.id);
      // 刷新数据源列表以更新测试状态
      await fetchDataSources();
    } catch (error: any) {
      // 错误已在API服务中处理
    }
  }, [fetchDataSources]);

  /**
   * 批量删除
   */
  const handleBatchDelete = useCallback(async () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请选择要删除的数据源');
      return;
    }

    try {
      await datasourceApi.batchDeleteDatasources(selectedRowKeys);
      setSelectedRowKeys([]);
      // 刷新数据源列表
      await fetchDataSources();
    } catch (error: any) {
      // 错误已在API服务中处理
    }
  }, [selectedRowKeys, fetchDataSources]);

  /**
   * 批量测试
   */
  const handleBatchTest = useCallback(async () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请选择要测试的数据源');
      return;
    }

    try {
      await datasourceApi.batchTestDatasources({ datasource_ids: selectedRowKeys });
      setSelectedRowKeys([]);
      // 刷新数据源列表
      await fetchDataSources();
    } catch (error: any) {
      // 错误已在API服务中处理
    }
  }, [selectedRowKeys, fetchDataSources]);

  /**
   * 批量启用/禁用
   */
  const handleBatchToggle = useCallback(async (enable: boolean) => {
    if (selectedRowKeys.length === 0) {
      message.warning(`请选择要${enable ? '启用' : '禁用'}的数据源`);
      return;
    }

    try {
      await datasourceApi.batchToggleDatasources(selectedRowKeys, enable);
      setSelectedRowKeys([]);
      // 刷新数据源列表
      await fetchDataSources();
    } catch (error: any) {
      // 错误已在API服务中处理
    }
  }, [selectedRowKeys, fetchDataSources]);

  /**
   * 表格列配置 - 使用useMemo优化性能
   */
  const columns: ColumnsType<DataSource> = useMemo(() => [
    {
      title: '数据源名称',
      dataIndex: 'display_name',
      key: 'display_name',
      width: 200,
      fixed: 'left',
      render: (text: string, record: DataSource) => (
        <div>
          <div style={{ fontWeight: 500 }}>{text}</div>
          <div style={{ fontSize: '12px', color: '#666' }}>{record.name}</div>
        </div>
      )
    },
    {
      title: '数据库类型',
      dataIndex: 'type',
      key: 'type',
      width: 120,
      render: (type: DatabaseType) => (
        <Tag color="blue">
          {DatabaseTypeLabels[type]}
        </Tag>
      ),
      filters: Object.entries(DatabaseTypeLabels).map(([value, label]) => ({
        text: label,
        value
      })),
      filteredValue: selectedType ? [selectedType] : null,
      onFilter: () => true // 由前端筛选处理
    },
    {
      title: '连接地址',
      dataIndex: 'connection_string_masked',
      key: 'connection_string_masked',
      width: 250,
      ellipsis: {
        showTitle: false
      },
      render: (text: string) => (
        <Tooltip title={text} placement="topLeft">
          <Text ellipsis>{text}</Text>
        </Tooltip>
      )
    },
    {
      title: '状态',
      dataIndex: 'is_active',
      key: 'is_active',
      width: 100,
      render: (isActive: boolean) => (
        <Tag color={isActive ? 'success' : 'default'}>
          {isActive ? '启用' : '禁用'}
        </Tag>
      ),
      filters: [
        { text: '启用', value: true },
        { text: '禁用', value: false }
      ],
      filteredValue: selectedStatus !== undefined ? [selectedStatus] : null,
      onFilter: () => true
    },
    {
      title: '健康状态',
      dataIndex: 'is_healthy',
      key: 'is_healthy',
      width: 120,
      render: (isHealthy: boolean, record: DataSource) => (
        <div>
          <Tag
            color={isHealthy ? 'success' : 'error'}
            icon={isHealthy ? <CheckCircleOutlined /> : <CloseCircleOutlined />}
          >
            {isHealthy ? '健康' : '异常'}
          </Tag>
          <div style={{ fontSize: '12px', color: '#666', marginTop: '2px' }}>
            <Tag color={TestStatusColors[record.last_test_status]} size="small">
              {TestStatusLabels[record.last_test_status]}
            </Tag>
          </div>
        </div>
      )
    },
    {
      title: '最后测试',
      dataIndex: 'last_test_at',
      key: 'last_test_at',
      width: 160,
      render: (time: string | null, record: DataSource) => (
        <div>
          <div style={{ fontSize: '12px' }}>
            {time ? new Date(time).toLocaleString() : '从未测试'}
          </div>
          {record.last_test_message && (
            <Tooltip title={record.last_test_message}>
              <div style={{
                fontSize: '11px',
                color: '#666',
                marginTop: '2px',
                overflow: 'hidden',
                textOverflow: 'ellipsis',
                whiteSpace: 'nowrap',
                maxWidth: '140px'
              }}>
                {record.last_test_message}
              </div>
            </Tooltip>
          )}
        </div>
      )
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      width: 160,
      render: (time: string) => new Date(time).toLocaleString()
    },
    {
      title: '操作',
      key: 'actions',
      width: 200,
      fixed: 'right',
      render: (_, record: DataSource) => (
        <Space size="small">
          <ActionGuard permission="datasource.test">
            <Tooltip title="测试连接">
              <Button
                type="text"
                size="small"
                icon={<ExperimentOutlined />}
                onClick={() => openTestModal(record)}
              />
            </Tooltip>
          </ActionGuard>

          <ActionGuard permission="datasource.update">
            <Tooltip title="编辑">
              <Button
                type="text"
                size="small"
                icon={<EditOutlined />}
                onClick={() => openModal(record)}
              />
            </Tooltip>
          </ActionGuard>

          <ActionGuard permission="datasource.delete">
            <Popconfirm
              title="确认删除"
              description={`确定要删除数据源"${record.display_name}"吗？`}
              onConfirm={() => handleDelete(record.id)}
              okText="确定"
              cancelText="取消"
            >
              <Tooltip title="删除">
                <Button
                  type="text"
                  size="small"
                  danger
                  icon={<DeleteOutlined />}
                />
              </Tooltip>
            </Popconfirm>
          </ActionGuard>

          <Dropdown
            menu={{
              items: [
                {
                  key: 'test',
                  label: '快速测试',
                  icon: <ExperimentOutlined />,
                  onClick: () => handleTest(record),
                  disabled: !permissions.canTest
                },
                {
                  key: 'toggle',
                  label: record.is_active ? '禁用' : '启用',
                  onClick: () => datasourceApi.batchToggleDatasources([record.id], !record.is_active),
                  disabled: !permissions.canUpdate
                }
              ]
            }}
            trigger={['click']}
          >
            <Button type="text" size="small" icon={<MoreOutlined />} />
          </Dropdown>
        </Space>
      )
    }
  ], [selectedType, selectedStatus, permissions, openModal, openTestModal, handleDelete, handleTest]);

  /**
   * 行选择配置
   */
  const rowSelection = useMemo(() => ({
    selectedRowKeys,
    onChange: (newSelectedRowKeys: React.Key[]) => {
      setSelectedRowKeys(newSelectedRowKeys as number[]);
    },
    getCheckboxProps: (record: DataSource) => ({
      disabled: false,
      name: record.name
    })
  }), [selectedRowKeys]);

  /**
   * 批量操作菜单
   */
  const batchActionMenuItems = useMemo(() => [
    {
      key: 'test',
      label: '批量测试',
      icon: <ExperimentOutlined />,
      onClick: handleBatchTest,
      disabled: !permissions.canTest || selectedRowKeys.length === 0
    },
    {
      key: 'enable',
      label: '批量启用',
      icon: <CheckCircleOutlined />,
      onClick: () => handleBatchToggle(true),
      disabled: !permissions.canUpdate || selectedRowKeys.length === 0
    },
    {
      key: 'disable',
      label: '批量禁用',
      icon: <CloseCircleOutlined />,
      onClick: () => handleBatchToggle(false),
      disabled: !permissions.canUpdate || selectedRowKeys.length === 0
    },
    {
      type: 'divider' as const
    },
    {
      key: 'delete',
      label: '批量删除',
      icon: <DeleteOutlined />,
      danger: true,
      onClick: () => {
        Modal.confirm({
          title: '确认批量删除',
          content: `确定要删除选中的 ${selectedRowKeys.length} 个数据源吗？`,
          okText: '确定',
          cancelText: '取消',
          onOk: handleBatchDelete
        });
      },
      disabled: !permissions.canDelete || selectedRowKeys.length === 0
    }
  ], [permissions, selectedRowKeys.length, handleBatchTest, handleBatchToggle, handleBatchDelete]);



  // 如果没有查看权限，显示无权限提示
  if (!permissions.canView) {
    return (
      <div style={{ textAlign: 'center', padding: '50px' }}>
        <QuestionCircleOutlined style={{ fontSize: '48px', color: '#ff4d4f' }} />
        <div style={{ marginTop: '16px' }}>您没有权限访问数据源管理</div>
      </div>
    );
  }

  return (
    <PermissionGuard permission="datasource.view">
      <div style={{ padding: '24px' }}>
        {/* 页面标题 */}
        <div style={{ marginBottom: '24px' }}>
          <Title level={2} style={{ margin: 0 }}>
            <DatabaseOutlined style={{ marginRight: '8px', color: '#1890ff' }} />
            数据源管理
          </Title>
          <Text type="secondary" style={{ fontSize: '14px' }}>
            管理数据库连接配置，支持MySQL、PostgreSQL、Oracle、SQL Server、Doris等多种数据库
          </Text>
        </div>

        {/* 操作栏 */}
        <Card style={{ marginBottom: '16px' }}>
          <Row gutter={[16, 16]} align="middle">
            <Col flex="auto">
              <Space size="middle">
                {/* 搜索框 */}
                <Search
                  placeholder="搜索数据源名称、主机地址..."
                  allowClear
                  style={{ width: 300 }}
                  onSearch={handleSearch}
                  onChange={(e) => {
                    if (!e.target.value) {
                      handleSearch('');
                    }
                  }}
                />

                {/* 数据库类型筛选 */}
                <Select
                  placeholder="数据库类型"
                  allowClear
                  style={{ width: 150 }}
                  value={selectedType}
                  onChange={(value) => handleFilterChange('type', value)}
                >
                  {Object.entries(DatabaseTypeLabels).map(([value, label]) => (
                    <Option key={value} value={value}>
                      {label}
                    </Option>
                  ))}
                </Select>

                {/* 状态筛选 */}
                <Select
                  placeholder="状态"
                  allowClear
                  style={{ width: 120 }}
                  value={selectedStatus}
                  onChange={(value) => handleFilterChange('status', value)}
                >
                  <Option value={true}>启用</Option>
                  <Option value={false}>禁用</Option>
                </Select>

                {/* 测试状态筛选 */}
                <Select
                  placeholder="测试状态"
                  allowClear
                  style={{ width: 120 }}
                  value={selectedTestStatus}
                  onChange={(value) => handleFilterChange('testStatus', value)}
                >
                  {Object.entries(TestStatusLabels).map(([value, label]) => (
                    <Option key={value} value={value}>
                      {label}
                    </Option>
                  ))}
                </Select>
              </Space>
            </Col>

            <Col>
              <Space>
                {/* 批量操作 */}
                {selectedRowKeys.length > 0 && (
                  <Badge count={selectedRowKeys.length} size="small">
                    <Dropdown
                      menu={{ items: batchActionMenuItems }}
                      trigger={['click']}
                    >
                      <Button>
                        批量操作 <MoreOutlined />
                      </Button>
                    </Dropdown>
                  </Badge>
                )}

                {/* 刷新按钮 */}
                <Button
                  icon={<ReloadOutlined />}
                  onClick={() => fetchDataSources(true)}
                  loading={loading}
                >
                  刷新
                </Button>



                {/* 创建按钮 */}
                <ActionGuard permission="datasource.create">
                  <Button
                    type="primary"
                    icon={<PlusOutlined />}
                    onClick={() => openModal()}
                  >
                    新建数据源
                  </Button>
                </ActionGuard>
              </Space>
            </Col>
          </Row>
        </Card>

        {/* 数据表格 */}
        <Card>
          <Table<DataSource>
            columns={columns}
            dataSource={datasources}
            rowKey="id"
            loading={loading}
            rowSelection={rowSelection}
            pagination={{
              ...pagination,
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: (total, range) =>
                `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
              pageSizeOptions: ['10', '20', '50', '100']
            }}
            onChange={handleTableChange}
            scroll={{ x: 1400 }}
            size="middle"
          />
        </Card>

        {/* 创建/编辑模态框 */}
        <Modal
          title={
            <Space>
              <DatabaseOutlined />
              {editingDataSource ? '编辑数据源' : '新建数据源'}
            </Space>
          }
          open={isModalVisible}
          onCancel={closeModal}
          footer={null}
          width={800}
          destroyOnClose
        >
          <DataSourceForm
            dataSource={editingDataSource || undefined}
            onSubmit={handleSubmit}
            onCancel={closeModal}
            loading={loading}
          />
        </Modal>

        {/* 连接测试模态框 */}
        <DataSourceTestModal
          visible={isTestModalVisible}
          dataSource={testingDataSource || undefined}
          onClose={closeTestModal}
        />
      </div>
    </PermissionGuard>
  );
};

export default DataSourceManagement;
